package com.kylin.common.taglib;

import java.util.List;
import java.util.Locale;

import javax.servlet.jsp.JspException;

import org.apache.log4j.Logger;
import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;

import com.kylin.common.dict.ISelectOption;
import com.kylin.common.dict.orm.Dict;
import com.kylin.common.exception.SystemException;
import com.kylin.common.util.MemObjFactory;
import com.kylin.common.util.UTool;
import com.kylin.common.util.UUID;

/**
 * 构造二级下拉菜单的标签类
 * 比如 产品类别下拉菜单
 * @author ly
 *
 */
public class CascadingTag extends SelectTag{
	protected static Logger log = Logger.getLogger(CascadingTag.class);
	
	private String selectParent;
	private String label;
	String value;
	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public int doStartTag() throws JspException {

		// pageContext.setAttribute("taglib.html.AllLanguageSelectTag", this);
		try {
			setValueByFormValue();
			try {
				getMatchValue();
			} catch (Exception e) {
				throw new JspException(e);
			}
		//	pageContext.getOut().println(getStartElement());
			try {
				pageContext.getOut().println(getOptions());
			} catch (Exception e) {
				e.printStackTrace();
				log.error("构造二级下拉菜单异常："+e,e);
			}
			pageContext.getOut().println("</select>");
		} catch (Exception e) {
			log.error("构造 二级 下拉菜单 异常："+e,e);
		}
		return this.EVAL_PAGE;
	}
	
	protected String getOptions() throws InstantiationException, IllegalAccessException,
			ClassNotFoundException {
		label = getLabel();

		List datas = null;
		if (listName != null)
			datas = (List) pageContext.getAttribute(listName);
		else if (dictName != null) {
			if (language == null || language.equals("")){
				Locale local = (Locale) pageContext.getAttribute(Globals.LOCALE_KEY, pageContext.SESSION_SCOPE);
				if(local != null)
			    	language = local.toString();
			}
			try {
				if ("all".equalsIgnoreCase(language))
					datas = MemObjFactory.getDict(dictName);
				else
					datas = MemObjFactory.getDict(dictName, language);
			} catch (SystemException e) {
				datas = null;
			}
		} else {
			throw new SystemException("未指定下拉菜单的数据源，请定义listName 或 dictName");
		}
		if(datas == null)
			return "";
		StringBuffer sb1 = new StringBuffer();
		StringBuffer sb2 = new StringBuffer();
		for (int i = 0; i < datas.size(); i++) {
			Dict dict = (Dict) datas.get(i);
			String dictName = dict.getName();
			dictName = dictName.replaceAll("'", "`");
			if (dict.getParent() == null) {
				if (sb1.length() > 1)
					sb1.append(",");
				sb1.append("\n  new SubSelectObj('").append(dict.getId()).append("','");
				sb1.append("").append("','");
				sb1.append(dictName).append("')");
			} else {
				if (sb2.length() > 1)
					sb2.append(",");
				sb2.append("\n  new SubSelectObj('").append(dict.getId()).append("','");
				sb2.append(dict.getParent().getId()).append("','");
				sb2.append(dictName).append("')");
			}
		}
		
		String selectId = UUID.create("select");
		StringBuffer content = new StringBuffer();
		content.append("<select name=\"").append(name).append("\" ");
		content.append("  id=\"").append(selectId).append("\" ");
		content.append(prepareEventHandlers());
		try {
			content.append(prepareStyles());
		} catch (JspException e) {
			e.printStackTrace();
		}
		if (selectParent != null && selectParent.equals("false"))
			content.append("       onchange=\"checkCascadSelect(this)\"  ");
		content.append("    > ");
		content.append("<option value=''>-- ").append(label).append(" --</option>");
		content.append("  </select>");
		content.append("  <script src=\"/script/kylin.js\"></script>");
		content.append("  <script>");
		content.append("      \n var "+ name +"ParentArray = new Array(" + sb1 + ");  ");
		content.append("      \n var "+ name +"SubArray = new Array(" + sb2 + ");     ");
		content.append("      \n var theCatSelect =  document.getElementById(\""+selectId+"\");     ");
		content.append("      \n setCascadSelect("+ name +"ParentArray,"+ name +"SubArray,theCatSelect);  ");
		content.append("      \n setSelectValue(document.getElementById('"+selectId+"'),'"+value+"')");
		content.append("   </script>  ");
		return content.toString();
	}
	private String getLabel(){
		if(label == null || label.equals(""))
			return "";
		Locale locale = (Locale) pageContext.getAttribute(Globals.LOCALE_KEY,
				pageContext.SESSION_SCOPE);
		if(language != null && !language.equals("") ) {
			locale  = UTool.getLocaleByLang(language);
		}
		MessageResources mess = MessageResources.getMessageResources("message");
		String messStr = mess.getMessage(locale,label);
		if(messStr == null)
			messStr = label;
		return messStr;
	}
	private String getStartElement() throws JspException {
		StringBuffer sb = new StringBuffer("<select");
		sb.append(" name=\"");
		sb.append(this.name);
		sb.append("\"");
		if (multiple != null)
			sb.append(" multiple=\"multiple\"");
		if (size != null) {
			sb.append(" size=\"");
			sb.append(size);
			sb.append("\"");
		}
		sb.append(prepareEventHandlers());
		sb.append(prepareStyles());
		sb.append(">");
		return sb.toString();
	}

	public String getSelectParent() {
		return selectParent;
	}

	public void setSelectParent(String selectParent) {
		this.selectParent = selectParent;
	}

	public void setLabel(String label) {
		this.label = label;
	}

}
